package com.itita.weibo.ui;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;

import weibo4andriod.Comment;
import weibo4andriod.Count;
import weibo4andriod.Status;
import weibo4andriod.User;
import weibo4andriod.WeiboException;
import android.app.Activity;
import android.content.Intent;
import android.graphics.Bitmap;
import android.graphics.drawable.BitmapDrawable;
import android.graphics.drawable.Drawable;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.Window;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.RelativeLayout;
import android.widget.TextView;
import android.widget.Toast;

import com.itita.weibo.manager.IWeiboActivity;
import com.itita.weibo.manager.MainService;
import com.itita.weibo.model.StatusAdapter;
import com.itita.weibo.model.Task;
import com.itita.weibo.util.WeiboUtil;

 
/**
 * 查看某一具体的微博信息
 * 
 * @author 焦明  2010-5-5 12：30
 *
 */
public final class ViewWeiboActivity extends Activity implements OnClickListener,IWeiboActivity{

	public static final int REFRESH = 0;
	
	private static final int COMMENT = 1;//评论
	
	private static final int FORWARD = 2;
	
	public static final int FAV = 3;
	
	private static final int MORE = 4;
	
	private static final int USER = 5;
	
	private static final int COMMENTLIST = 6;//评论列表
	
	public static final int REF_ICON_OR_WEIBO_IMAGE = 7;//更新头像
	
	private Status status;
	
	private Button btnTweetRedirect;
	 
	private  Button btnTweetComment;
	
	private TextView tvFav;
	
	private ImageView tweet_upload_pic2 ;
	
	private ImageView weiboContentPic;
	
	private long retweetedId;
	
	public void init() {
		this.initControlsAndAddControlsEvent();
//		new Thread(new LoadImageThread(status)).start();
	}

	 
	public void refresh(Object... param) {
		switch ((Integer)param[0]) {
			case REFRESH:
				if(param[1] == null){
					WeiboUtil.myToastShow(this, "网络连接失败");
					return;
				}
			    ArrayList<Count> counts = (ArrayList<Count> ) param[1];
			    status.setRetweetedNum(counts.get(0).getRt());
			    status.setCommNum(counts.get(0).getComments());
			    this.btnTweetRedirect.setText(new StringBuffer().append("转发").append(String.valueOf(counts.get(0).getRt())).toString());
				this.btnTweetComment.setText(new StringBuffer().append("转发").append(String.valueOf(counts.get(0).getComments())).toString());
				break;
				
			case FAV:
				if(param[1] == null){
					WeiboUtil.myToastShow(this, "收藏失败");
					return;
				}
				this.tvFav.setText(R.drawable.detail_fav_normal);
				
				break;
		    
			case REF_ICON_OR_WEIBO_IMAGE: //
				if(MainService.getAllImage(retweetedId) != null){
					this.tweet_upload_pic2.setImageBitmap(MainService.getAllImage(retweetedId));
				} 
				long statusId = status.getId();
				if(MainService.getAllImage(statusId) != null){
					this.weiboContentPic.setImageBitmap(MainService.getAllImage(statusId));
				} 
				
				break;
				
			default:
				break;
		}
		
	}
	
	protected void onCreate(Bundle savedInstanceState) {
		
		super.onCreate(savedInstanceState);
		//取消标题栏
		this.requestWindowFeature(Window.FEATURE_NO_TITLE);
		//获取传递过来的微博信息
		status=(Status)this.getIntent().getSerializableExtra("status");
		setContentView(R.layout.detailweibo);
		
		MainService.addActivity(this);
	}


	@Override
	public void initControlsAndAddControlsEvent() {
	//为用户布局添加监听事件
		
		//标签部分的布局<!-- 标签部分 --> 
		RelativeLayout tweet_profile = (RelativeLayout) findViewById(R.id.tweet_profile);
		tweet_profile.setTag(USER);
		tweet_profile.setOnClickListener(this);
		
		
		View title = findViewById(R.id.detailweibo_title);
		Button back = (Button) title.findViewById(R.id.title_bt_left);
	    //返回
//		back.setText(R.string.imageviewer_back);
		
		back.setBackgroundResource(R.drawable.title_back);
		
		back.setOnClickListener(new Button.OnClickListener(){

			@Override
			public void onClick(View v) {
				ViewWeiboActivity.this.finish();
			}
			
		});
		//主页
		Button home = (Button) title.findViewById(R.id.title_bt_right);
	    home.setBackgroundResource(R.drawable.title_home);
	    home.setVisibility(View.GONE);
		((TextView) title.findViewById(R.id.textView))
				.setText(R.string.title_mblog_content);
		
//		 final ImageView imageViewTitle = (ImageView) title.findViewById(R.id.imageViewTitle);
//		 imageViewTitle.setImageResource(R.drawable.status_content);
		 
	   weiboContentPic = (ImageView) this.findViewById(R.id.weiboContentPic);
		
		String bdiddlePic = status.getBmiddle_pic();
		
		User user = status.getUser();
		
		int userId = user.getId();
		
		long statusId = status.getId();
		
		if(WeiboUtil.strIsNotEmpty(bdiddlePic)){
			//将weiboContentPic设置为显示的
			weiboContentPic.setVisibility(View.VISIBLE);
			weiboContentPic.setImageResource(R.drawable.loading);
			if(MainService.getAllImage(statusId) == null){
				HashMap hashMap = new HashMap();
				hashMap.put("statusId", statusId);
				Task task = new Task(Task.TASK_GET_WEIBO_IMAGE_FOR_VIEW_WEIBO_INFO, hashMap);
				MainService.newTaskToTaskQueneHead(task);
				
			}else{
				weiboContentPic.setImageBitmap(MainService.getAllImage(statusId));
			}
		}
		
		
		
		//<!-- 昵称 -->
		TextView tweet_profile_name = (TextView) findViewById(R.id.tweet_profile_name);
		//设置昵称
		tweet_profile_name.setText(user.getName());
		
		//微博内容
		TextView tweet_message = (TextView) findViewById(R.id.tweet_message);
		//给微博设置内容
		tweet_message.setText(status.getText());
	    //标志微博中的链接
		WeiboUtil.addURLSpan(status.getText(), tweet_message);
		 
		//<!-- 头像 -->
		ImageView tweet_profile_preview = (ImageView) findViewById(R.id.tweet_profile_preview);
		
		ImageView tweet_upload_pic = (ImageView) findViewById(R.id.tweet_upload_pic);
		
		TextView tweet_updated =(TextView) findViewById(R.id.tweet_updated);
		
		//时间
		tweet_updated.setText(status.getCreatedAt().toLocaleString());
		//<!-- 是否是VIP -->
		ImageView tweet_profile_vip = (ImageView) findViewById(R.id.tweet_profile_vip);
		
		if(user.isVerified()){//如果是VIP
//			tweet_profile_vip.setVisibility(View.VISIBLE);
			////System.out.println("--------VIP-------");
			tweet_profile_vip.setVisibility(View.VISIBLE);
		}
		
		//如果头像已经下载
	    if(MainService.allIcon.get(userId)!=null)
        {	
	    	tweet_profile_preview.setImageBitmap(MainService.allIcon.get(userId));
        }else
        {// 设定缺省的图片
        	tweet_profile_preview.setImageResource(R.drawable.portrait);	
        }
		
	 
		//查看转发按钮
		btnTweetRedirect  = (Button) this.findViewById(R.id.btnTweetRedirect);
        btnTweetComment = (Button) this.findViewById(R.id.btnTweetComment);
		
		btnTweetComment.setText(new StringBuffer().append("评论").append(status.getCommNum()));
		btnTweetRedirect.setText(new StringBuffer().append("转发").append(status.getRetweetedNum()));
 
        //添加查看评论事件
        btnTweetComment.setTag(COMMENTLIST);
        btnTweetComment.setOnClickListener(this);
		
        Status retweetedStatus = status.getRetweeted_status();
		
		//如果转发内容不为空
		if(retweetedStatus !=null){
			//转发内容的布局
			View src_text_block = findViewById(R.id.src_text_block);
			src_text_block.setVisibility(View.VISIBLE);
			
			//转发内容
			TextView tweet_oriTxt = (TextView)src_text_block.findViewById(R.id.tweet_oriTxt);
			//设置转发的内容
			tweet_oriTxt.setText(retweetedStatus.getText());
			//转发内容中的图片
		   tweet_upload_pic2 = (ImageView)src_text_block.findViewById(R.id.tweet_upload_pic2);
		    
			String retweetedBdmddlePic = retweetedStatus.getBmiddle_pic();
			User retweetedUser = retweetedStatus.getUser();
//			int retweetedUserId = retweetedUser.getId();
			this.retweetedId = retweetedStatus.getId();
			if(WeiboUtil.strIsNotEmpty(retweetedBdmddlePic)){
				tweet_upload_pic2.setVisibility(View.VISIBLE);
				try {
					if(MainService.getAllImage(retweetedId) == null){
						//设置缺省图片
						tweet_upload_pic2.setImageResource(R.drawable.loading);
						//启动线程加载图片
//						new LoadImageThread(retweetedStatus).start();
						HashMap hashMap = new HashMap();
						hashMap.put("statusId", retweetedId);
						Task task = new Task(Task.TASK_GET_WEIBO_IMAGE_FOR_VIEW_WEIBO_INFO, hashMap);
						MainService.newTaskToTaskQueneHead(task);
						
					}else{
						//设置图片
						tweet_upload_pic2.setImageBitmap(MainService.getAllImage(retweetedId));
					}
				    
				} catch (Exception e) {
					e.printStackTrace();
				}
			}
		}
		
		TextView tvRefresh = (TextView) findViewById(R.id.tvReload);
		tvRefresh.setTag(REFRESH);
		tvRefresh.setOnClickListener(this);
	
		TextView tvComment = (TextView) findViewById(R.id.tvComment);
		tvComment.setTag(COMMENT);
		tvComment.setOnClickListener(this);
		
		TextView tvForward = (TextView) findViewById(R.id.tvForward);
		tvForward.setTag(FORWARD);
		tvForward.setOnClickListener(this);
		
		 this.tvFav = (TextView) findViewById(R.id.tvFav);
		tvFav.setTag(FAV);
		tvFav.setOnClickListener(this);
		
		TextView tvMore = (TextView) findViewById(R.id.tvMore);
		tvMore.setTag(MORE);
		tvMore.setOnClickListener(this);
//		init();
	}

	public void onClick(View v) {
		int tag = (Integer) v.getTag();
		Intent it = null;
		HashMap param = null;
		switch (tag) {
		case REFRESH: //刷新
//			Toast.makeText(this, "REFRESH", 3000).show();
		    param = new HashMap();
			param.put("statusId", status.getId());
			Task ts = new Task(Task.TASK_REFRESH_WEIBO, param);
			MainService.mainService.newTaskToTaskQueneHead(ts);
			break;
			
		case COMMENT: //评论
//			Toast.makeText(this, "转发", 3000).show();
			it = new Intent(this, CommentActivity.class);
			it.putExtra("statusId", status.getId());
			startActivity(it);
			break;
			
		case FORWARD: //转发
//			Toast.makeText(this, "转发", 3000).show();
			it = new Intent(this, RepostBlogActivity.class);
//			it.putExtra("statusId", status.getId());
			 it.putExtra("status",status);
			startActivityForResult(it, 2);
			break;
			
		case FAV: //收场
			Toast.makeText(this, "收藏", 3000).show();
			HashMap  params = new HashMap();
			params.put("statusId", status.getId());
			Task ts2 = new Task(Task.TASK_FAV_WEIBO, params );
			MainService.mainService.newTaskToTaskQueneHead(ts2);
			break;
			
		case MORE: //更多
			Toast.makeText(this, "MORE", 3000).show();
			break;
			
		case USER:
//			it = new Intent(this,UserActivity.class);
//			it.putExtra("user", status.getUser());
//			startActivity(it);
			break;
			
		case COMMENTLIST:
//			Toast.makeText(this, "COMMENTLIST", 3000).show();
			Intent intent = new Intent();
			intent.setClass(this, ListCommentsActivity.class);
			//将评论列表放入容器AppContainer.commentsList中
//			WeiboUtil.commentsList4OneStatus = this.comments;
			Bundle bundle = new Bundle();
			bundle.putLong("statusId", status.getId());
			intent.putExtras(bundle);
			startActivityForResult(intent, 3);
			break;
		}
	}
	
//   private Handler myHandler =  new Handler(){
//	  public void handleMessage(android.os.Message msg) {
//		  //更新
//		  tweet_upload_pic2.setImageDrawable((Drawable) msg.obj);
//	  }
//   };
   
  
  
	//一个现成来加载微博中所涉及的图片
//   private class LoadImageThread extends Thread {
//	 
//	 private Status status;
//	 
//	 private Bitmap bitmapDrawable;
//	 
//	 public LoadImageThread(Status status){
//		this.status = status;
//	 }  
//	 
//	 Message message = myHandler.obtainMessage();
//	 
//	 public void run() {
//		while(true){
//			try {
//				bitmapDrawable = MainService.getAllImage(status.getUser().getId());
//			    if(bitmapDrawable != null){
//			    	break;
//			    }
//			} catch (Exception e) {
//				// TODO: handle exception
//			}
//			
//		} 
//		message.obj = bitmapDrawable;
//		//将message压入Message
//		myHandler.sendMessage(message);
//	 }
//  };
	 
	protected void onDestroy() {
		super.onDestroy();
	}

	protected void onResume() {
		super.onResume();
		init();
	}


}
